<?php
/**
 * Created by PhpStorm.
 * User: l-eru
 * Date: 2018/7/9
 * Time: 16:39
 */

namespace App\Library;


use Monolog\Handler\StreamHandler;

class TanBaHandler extends StreamHandler
{
    protected $path;      // 日志文件路径
    protected $mac;       // TanBa mac地址
    protected $extension; // 文件后缀
    protected $reloadAt;  // 日志文件重新生成时间
    protected $reload;    // 是否重新生成日志文件

    public function __construct($path, $mac, $extension = 'log')
    {
        $this->path = $path;
        $this->mac = $mac;
        $this->extension = $extension;
        $this->reloadAt = new \DateTime('tomorrow');

        parent::__construct($this->getFilename());
    }

    protected function write(array $record)
    {
        // on the first record written, if the log is new, we should rotate (once per day)
        if (null === $this->reload) {
            $this->reload = !file_exists($this->url);
        }

        if ($this->reloadAt < $record['datetime']) {
            $this->reload = true;
            $this->close();
        }

        parent::write($record);
    }

    public function close()
    {
        parent::close();

        if (true === $this->reload) {
            $this->reload();
        }
    }

    protected function reload()
    {
        $this->reloadAt = new \DateTime('tomorrow');
        $this->url = $this->getFilename();
    }

    /**
     * 获取日志要存储的文件路径
     * @return string
     */
    protected function getFilename()
    {
        return $this->path . date('/Y-m/d/') .
            $this->mac . '.' . $this->extension;
    }
}